package com.ehsy.controller;

import com.ehsy.modo.R;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 */
@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public R<Object> handleError(HttpServletRequest request) {

        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
        if (status != null && Integer.parseInt(status.toString()) == HttpStatus.NOT_FOUND.value()) {
            R<Object> r = new R<>();
            r.setCode(404);
            r.setMsg("页面不存在");
            return r;
        }else if (exception != null){
            R<Object> r = new R<>();
            r.setCode(500);
            r.setMsg(exception.getMessage());
            return r;
        }else {
            R<Object> r = new R<>();
            r.setCode(500);
            r.setMsg("未知异常");
            return r;
        }
    }
}